package com.changan.controller;

import com.changan.entity.User;
import com.changan.service.UserService;
import com.changan.vo.LoginVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
/*import javax.validation.Valid;*/

/**
 * 登录的控制器
 * 在演示git的时候添加的注释
 * 使用idea更新和提交代码
 * ghfffhfhgf  这是test分支添加的代码
 */
@Controller
public class LoginController {

    @Autowired
    private UserService userService;

    /**
     * 当访问 / 获取 /toLogin的时候跳转到登录页面
     * @return 视图名称
     */
    @RequestMapping({"/","/toLogin"})
    public String toLogin(){
        return "login";
    }

    @RequestMapping("/login")
    public String login(/*@Valid*/ LoginVO loginVO,
                        Model model,
                        HttpServletRequest request){
        User user = userService.login(loginVO.getUserCode());
        if(user==null){
            model.addAttribute("error","当前登录账号不存在");
            return "login";
        }
        if(!user.getUserpassword().equals(loginVO.getUserPassword())){
            model.addAttribute("error","登录密码错误");
            return "login";
        }
        //如果成功了,则需要添加到session中
        request.getSession().setAttribute("user",user);
        return "index";
    }

    /**
     * 功能描述: <br>
     * 〈注销〉
     * @Param: []
     * @Return: java.lang.String
     * @Author: Mr.Nie
     * @Date: 2021/12/1 14:00
     */
    @RequestMapping("/logout")
    public String logout(HttpServletRequest request){
        request.getSession().removeAttribute("user");
        //有点类似销毁session(关闭浏览器的操作)
        request.getSession().invalidate();
        return "login";
    }
}
